package com.xxc.hs.funActivity.chart;

import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AliyunApiClient {
    private static final String TAG = "AliyunApiClient";
    private final String endpoint;
    private final String apiPath;
    private final String method;
    private final String apiKey;
    private final OkHttpClient client;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final int MAX_RETRIES = 3;

    public interface ApiCallback {
        void onSuccess(String response);

        void onFailure(Exception e);
    }

    public AliyunApiClient(String endpoint, String apiPath, String method, String apiKey) {
        this.endpoint = endpoint;
        this.apiPath = apiPath;
        this.method = method;
        this.apiKey = apiKey;

        // 超时设置
        this.client = new OkHttpClient.Builder()
                .connectTimeout(45, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
    }

    public void executeRequest(String requestBody, ApiCallback callback) {
        new ApiRequestTask(callback).execute(requestBody);
    }

    private class ApiRequestTask extends AsyncTask<String, Void, String> {
        private final ApiCallback callback;
        private Exception lastException;
        private int retries = 0;

        public ApiRequestTask(ApiCallback callback) {
            this.callback = callback;
        }

        @Override
        protected String doInBackground(String... params) {
            String requestBody = params[0];
            String fullUrl = endpoint + apiPath;

            while (retries <= MAX_RETRIES) {
                retries++;
                try {
                    Log.d(TAG, "执行API请求 (重试: " + retries + "/" + MAX_RETRIES + ")");

                    RequestBody body = RequestBody.create(JSON, requestBody);
                    Request request = new Request.Builder()
                            .url(fullUrl)
                            .header("Authorization", "Bearer " + apiKey)
                            .header("Content-Type", "application/json")
                            .method(method, body)
                            .build();

                    try (Response response = client.newCall(request).execute()) {
                        if (!response.isSuccessful()) {
                            lastException = new IOException("HTTP错误: " + response.code() +
                                    ", 响应体: " + (response.body() != null ? response.body().string() : "无"));
                            return null;
                        }
                        return response.body().string();
                    }
                } catch (java.net.SocketTimeoutException e) {
                    lastException = e;
                    Log.w(TAG, "请求超时，准备重试 (" + retries + "/" + MAX_RETRIES + ")", e);
                    if (retries <= MAX_RETRIES) {
                        try {
                            long delay = 1000 * (1 << Math.min(retries, 3));
                            Log.d(TAG, "重试前等待 " + delay + "ms");
                            Thread.sleep(delay);
                        } catch (InterruptedException ignored) {
                        }
                    } else {
                        Log.e(TAG, "达到最大重试次数，放弃", e);
                        return null;
                    }
                } catch (IOException e) {
                    lastException = e;
                    Log.e(TAG, "网络错误", e);
                    return null;
                } catch (Exception e) {
                    lastException = e;
                    Log.e(TAG, "未知错误", e);
                    return null;
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            if (response != null) {
                callback.onSuccess(response);
            } else if (lastException != null) {
                callback.onFailure(lastException);
            } else {
                callback.onFailure(new Exception("未知错误"));
            }
        }
    }
}